import sys
sys.path.append("../")

from model.CommonDb import *
import datetime

class ChartsController:
    def __init__(self,args):
        self.args = args
        self.today = datetime.datetime.now().strftime("%Y-%m-%d")

    def run(self):
        if self.args["func"] == "getOption" and self.args["data"]["type"] == "oneline":
            return self.getOneLine(self.args["fields"],self.args["data"])
        elif self.args["func"] == "getOption" and self.args["data"]["type"] == "moreline":
            return self.getMoreLine(self.args["fields"], self.args["data"])
        elif self.args["func"] == "getOption" and self.args["data"]["type"] == "onebar":
            return self.getOneBar(self.args["fields"], self.args["data"])

    def getOneLine(self,fields,data):
        db = CommonDb(self.args["model"])
        rs = db.getAllColumns(fields)
        legend = []
        fieldmap = {}
        for col in fields:
            for row in rs:
                if row["field"] == col:
                    fieldmap[row["field"]] = row["comment"]
                    legend.append(row["comment"])

        whereChild = []
        for whereOption in data["w"].split("||"):
            whereOption2 = whereOption.split("|")
            whereChild.append(whereOption2[0] + "='" + str(whereOption2[1])+"'")
        datas = db.selectRowDataByWhere(",".join(fields)+","+data["t"]+","+data["x"]," and ".join(whereChild)+" order by count_day")
        xaxis = []
        for line in datas:
            if line[data["x"]] not in xaxis:
                xaxis.append(line[data["x"]])
        datamap = {}
        for col in fields:
            datamap[col] = []
            for line in datas:
                datamap[col].append(line[col])
        # print(legend)
        # print(datas)
        # print(xaxis)
        # print(datamap)
        optionstr = "var option1 = {"
        optionstr += "  title: {"
        optionstr += "      text: '"+ data["title"] +"'"
        optionstr += "  },"
        optionstr += "  tooltip: {"
        optionstr += "      trigger: 'axis'"
        optionstr += "  },"
        optionstr += "  legend: {"
        optionstr += "      data: " + str(legend)
        optionstr += "  },"
        optionstr += "  xAxis: {"
        optionstr += "      type: 'category',"
        optionstr += "      data: " + str(xaxis)
        optionstr += "  },"
        optionstr += "  yAxis: {"
        optionstr += "      type: 'value'"
        optionstr += "  },"
        optionstr += "  series: ["
        for key in datamap.keys():
            optionstr += "  {"
            optionstr += "      name: '"+ fieldmap[key] +"',"
            optionstr += "      type: 'line',"
            optionstr += "      data: " + str(datamap[key])
            optionstr += "  },"
        optionstr += " ]"
        optionstr += "}"
        return optionstr

    def getMoreLine(self,fields,data):
        db = CommonDb(self.args["model"])
        rs = db.getAllColumns(fields)
        fieldmap = {}
        for col in fields:
            for row in rs:
                if row["field"] == col:
                    fieldmap[row["field"]] = row["comment"]
        whereChild = []
        for whereOption in data["w"].split("||"):
            whereOption2 = whereOption.split("|")
            whereChild.append(whereOption2[0] + "='" + str(whereOption2[1])+"'")
        datas = db.selectRowDataByWhere(",".join(fields)+","+data["t"]+","+data["x"]," ("+" or ".join(whereChild)+") order by count_day")
        legend = []
        for line in datas:
            if line[data["t"]] not in legend:
                legend.append(line[data["t"]])
        xaxis = []
        for line in datas:
            if line[data["x"]] not in xaxis:
                xaxis.append(line[data["x"]])
        datamap = {}
        for col in legend:
            datamap[col] = []
            for line in datas:
                if line[data["t"]] == col:
                    datamap[col].append(line[data["y"]])
        #print(legend)
        #print(datas)
        #print(xaxis)
        #print(datamap)
        optionstr = "var option1 = {"
        optionstr += "  title: {"
        optionstr += "      text: '"+ data["title"] +"'"
        optionstr += "  },"
        optionstr += "  tooltip: {"
        optionstr += "      trigger: 'axis'"
        optionstr += "  },"
        optionstr += "  legend: {"
        optionstr += "      data: " + str(legend)
        optionstr += "  },"
        optionstr += "  xAxis: {"
        optionstr += "      type: 'category',"
        optionstr += "      data: " + str(xaxis)
        optionstr += "  },"
        optionstr += "  yAxis: {"
        optionstr += "      type: 'value'"
        optionstr += "  },"
        optionstr += "  series: ["
        for key in datamap.keys():
            optionstr += "  {"
            optionstr += "      name: '"+ str(key) +"',"
            optionstr += "      type: 'line',"
            optionstr += "      data: " + str(datamap[key])
            optionstr += "  },"
        optionstr += " ]"
        optionstr += "}"
        return optionstr

    def getOneBar(self,fields,data):
        db = CommonDb(self.args["model"])
        rs = db.getAllColumns(fields)
        fieldmap = {}
        for col in fields:
            for row in rs:
                if row["field"] == col:
                    fieldmap[row["field"]] = row["comment"]
        whereChild = []
        for whereOption in data["w"].split("||"):
            whereOption2 = whereOption.split("|")
            if whereOption2[1] == "today":
                whereChild.append(whereOption2[0] + "='" + self.today + "'")
            else:
                whereChild.append(whereOption2[0] + "='" + str(whereOption2[1]) + "'")
        datas = db.selectRowDataByWhere(",".join(fields) + "," + data["x"],
                                        " and ".join(whereChild) + " order by count_day")
        xaxis = []
        for line in datas:
            if line[data["x"]] not in xaxis:
                xaxis.append(line[data["x"]])
        datamap = {}
        values = []
        for col in xaxis:
            datamap[col] = []
            for line in datas:
                if line[data["x"]] == col:
                    if float(line[data["y"]]) < 0:
                        values.append('{value: ' + str(line[data["y"]]) + ', itemStyle: {color: "green"}}')
                    else:
                        values.append('{value: ' + str(line[data["y"]]) + ', itemStyle: {color: "red"}}')
        #print(datas)
        #print(xaxis)
        #print(values)
        optionstr = "var option1 = {"
        optionstr += "  title: {"
        optionstr += "      text: '" + data["title"] + "'"
        optionstr += "  },"
        optionstr += "  tooltip: {"
        optionstr += "      trigger: 'axis'"
        optionstr += "  },"
        optionstr += "  xAxis: {"
        optionstr += "      axisLabel: {"
        optionstr += "          interval: 0,"
        optionstr += "          rotate: 90"
        optionstr += "      },"
        optionstr += "      type: 'category',"
        optionstr += "      data: " + str(xaxis)
        optionstr += "  },"
        optionstr += "  yAxis: {"
        optionstr += "      type: 'value'"
        optionstr += "  },"
        optionstr += "  series: ["
        optionstr += "  {"
        optionstr += "      type: 'bar',"
        optionstr += "      data: " + str(values).replace("'","")
        optionstr += "  },"
        optionstr += " ]"
        optionstr += "}"
        return optionstr